package com.ys.controller;

import lombok.extern.log4j.Log4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>@description:shiro的测试类 </p>
 *
 * @className:
 * @author: yangshuang
 * @date: 2017/4/28 17:49
 * @version: v1.0
 */
@RequestMapping(value = "/shiro")
@RestController
@Log4j
public class ShiroController {

    @GetMapping("/aLogin")
    public String login(String username) {

       /* //token
        UsernamePasswordToken token = new UsernamePasswordToken(username,"123456");
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        //验证是否登录成功
        if (subject.isAuthenticated()) {
            System.out.println("登录认证");
        }
        else {
            System.out.println("认证失败");
        }
        return null;*/


        UsernamePasswordToken token = new UsernamePasswordToken(username, "123456");
        token.setRememberMe(true);
        //获取当前的Subject
        Subject currentUser = SecurityUtils.getSubject();


        try {
            //在调用了login方法后，SecurityManager会收到AuthenticationToken，并将其发送给已配置的Realm执行必须的认证检查
            //每个Realm都能在必要时对提交的AuthenticationTokens作出反应
            //所以这一步在调用login(token)方法时，它会走到MyRealm.doGetAuthenticationInfo()方法中，具体验证方式详见此方法
            System.out.println("对用户[" + username + "]进行登录验证...验证开始");
            currentUser.login(token);
            System.out.println("对用户[" + username + "]进行登录验证...验证通过");
        }catch (Exception e){
//            throw e.printStackTrace();;
            System.out.println("验证失败");
        }
        //验证是否登录成功
        if(currentUser.isAuthenticated()){
            System.out.println("用户[" + username + "]登录认证通过（这里可进行一些认证通过后的系统参数初始化操作）");
            return "main";
        }else{
            token.clear();
            return InternalResourceViewResolver.FORWARD_URL_PREFIX + "/";
        }
    }
    @GetMapping(value = "/helloa/{id}")
    public String say(@PathVariable(value = "id") Integer id, HttpServletRequest request) {
        String parameter = request.getParameter("id");
        log.info("/shiro/hello/{id}->id"+id);
        // System.out.println(id);
        // return girlProperties.getCupSize();
        return null;
    }
}
